package com.workManager.util;

import java.io.*;

/**
 * 
* @ClassName: SerializeUtil 
* @Description: 序列化辅助类
* @author xucan
* @date 2016年11月21日 下午12:53:12 
*
 */
public final class SerializeUtil {
    private SerializeUtil() {
    }

    /**
     * 序列化
     * 
     * @param object
     * @return
     */
    public static final byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        } finally {
            if(oos!=null){
                oos.close();
            }
            baos.close();
        }
    }

    /**
     * 反序列化
     * 
     * @param bytes
     * @return
     */
    public static final Object deserialize(byte[] bytes) throws IOException {
        return deserialize(bytes, Object.class);
    }

    /**
     * 反序列化
     * 
     * @param bytes
     * @return
     */
    @SuppressWarnings("unchecked")
    public static final <K> K deserialize(byte[] bytes, Class<K> cls) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(bais);
            return (K)ois.readObject();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        } finally {
            if(ois!=null){
                ois.close();
            }
            bais.close();
        }
    }
}
